﻿@inject NavigationManager NavManager

<Menu 
    Mode="MenuMode.Inline"
    DefaultSelectedKeys=@(selectedKeys)
    DefaultOpenKeys=@(openedKeys)>
    @foreach(var menu in menus)
    {
        <SubMenu Key=@menu.Path TitleTemplate=@(getFragment(menu))>
           @foreach(var smenu in menu.Children) {
            <MenuItem Key=@smenu.Path RouterLink=@smenu.Path>@smenu.Title</MenuItem>
           }
        </SubMenu> 
    }
</Menu>

@code {
    ZMenuItem[] menus=new ZMenuItem[] {
       new ZMenuItem { Title="主要", Icon="home",Path="main",Children=new ZMenuItem[] {
            new ZMenuItem { Title="主页", Path="/" },
            new ZMenuItem { Title="计数器", Path="/counter" }
       }},
       new ZMenuItem { Title="其他", Icon="windows",Path="other",Children=new ZMenuItem[] {
            new ZMenuItem { Title="天气", Path="/fetchData" },
            new ZMenuItem { Title="待办事项", Path="/todo" }
       }}
    };
    string[] selectedKeys;
    string[] openedKeys;

    private RenderFragment getFragment(ZMenuItem menu)
    {
        return @<span><Icon Type=@menu.Icon></Icon><span>@menu.Title</span></span>;
    }

    private string getParentPath(string path)
    {
        foreach(var menu in menus)
        {
            foreach(var smenu in menu.Children)
            {
                if(smenu.Path==path)
                    return menu.Path;
            }
        }
        return null;
    }

    protected override void OnInitialized()
    {
        string path=NavManager.Uri;
        var i=NavManager.BaseUri.Length-1;
        var j=path.IndexOf('?',i);
        if(j==-1) j=path.Length;
        path=path.Substring(i,j-i);
        Console.WriteLine(path);
        selectedKeys=new String[] {path};
        openedKeys=new String[] { getParentPath(path)};
    }
}
